
#include "precompiled.h"
#include "scriptplugin.h"
#include <extensions/context.h>

#include "script/contextimpl.h"
#include <scripting/scriptenvironment.h>
#include "engine.h"
#include "helper.h"
#include "windowsmanager.h"
#include "script/scriptenvironmentex.h"
#include <scripting/system/io/file.h>

class ScriptPluginPrivate{
public:
	ScriptPluginPrivate():
			environment(0)
	{}

	~ScriptPluginPrivate() {delete environment;}
	QFileInfo fileInfo;
	Opl::Scripting::ScriptEnvironment* environment;	
};

ScriptPlugin::ScriptPlugin(Optra::Extensions::Plugin::Type type, Optra::Extensions::Context* ctx, const QFileInfo& info, Opl::Core::EntityObject *parent) :
		Optra::Extensions::Plugin(type, ctx, parent), O_PRIVATE_CREATE(ScriptPlugin)
{
	O_D(ScriptPlugin);
	d->fileInfo = info;
	QFile scriptFile(info.absoluteFilePath());
	if (!scriptFile.open(QIODevice::ReadOnly)){
		LI.Error() << "Unable to open script file" << scriptFile.errorString();
		setErrorString(scriptFile.errorString());
		setValid(false);
		return;
	}

	QTextStream stream(&scriptFile);
	QString contents = stream.readAll();
	scriptFile.close();
	if (ctx == 0){
		Optra::Extensions::Context* ctx = new ContextImpl(0);
		ctx->process(info.absoluteDir());
		setContext(ctx);
	}

	d->environment = new ScriptEnvironmentEx(type == Optra::Extensions::Plugin::application ? ScriptEnvironmentEx::application : ScriptEnvironmentEx::plugin);
	d->environment->initialize();

//	switch(type)
//	{
//	case Optra::Extensions::Plugin::extension:
//		d->environment->registerObject("extension", this);
//		break;
//	case Optra::Extensions::Plugin::application:
//		d->environment->registerObject("application", this);
//		break;
//	}

	if (!d->environment->exec(contents, scriptFile.fileName(), false)){
		setValid(false);
		LI.Error() << "Unable to exec script file" << scriptFile.errorString();
		setErrorString(d->environment->errorString());
	}

}

bool ScriptPlugin::registerClass(Opl::Scripting::System::IO::File* file)
{
	return true;
}

ScriptPlugin::~ScriptPlugin()
{
	O_PRIVATE_DELETE;
}
